/**
 * 
 */
package wong.board.client.ui;

import java.util.Set;

import wong.board.client.util.IterableJSONObject;
import wong.board.client.util.JSONTool;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONObject;

/**
 * @author wong
 * 
 */
public class NotesPresenter extends Presenter<NotesPresenter.View, JSONObject> {

	private JSONObject notes;

	public NotesPresenter() {
		this((View) GWT.create(View.class));
	}

	public NotesPresenter(View view) {
		super(view);
	}

	@Override
	public void updateView(JSONObject newNotes) {
		if (newNotes != null) {
			merge(newNotes);
			getView().removeNotes();
			Set<String> noteNames = notes.keySet();
			for (String noteName : noteNames) {
				JSONObject note = notes.get(noteName).isObject();
				getView().addNote(noteName, note);
			}
		}
	}

	private JSONObject merge(JSONObject newNotes) {
		if (notes == null) {
			notes = newNotes;
		} else {
			IterableJSONObject<JSONObject> newNotesEntries = new IterableJSONObject<JSONObject>(newNotes);
			for (IterableJSONObject.Entry<JSONObject> entry : newNotesEntries) {
				JSONObject value = JSONTool.isObject(notes, entry.key);
				if (value == null) {
					value = entry.value;
				} else {
					value = JSONTool.merge(value, entry.value, true);
				}
				notes.put(entry.key, value);
			}
		}
		return notes;
	}

	public interface View extends Presenter.View {

		void removeNotes();

		void addNote(String label, JSONObject note);

	}

}
